package com.example.pattern.data

import android.app.Application
import android.graphics.Bitmap
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.pattern.R
import com.example.pattern.db.Picture
import com.example.pattern.utils.FileUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class PictureViewModel(application: Application):AndroidViewModel(application) {
    private var repository = Repository()
    val models = repository.loadDates()
    fun savePicture(picture: Picture){
        viewModelScope.launch(Dispatchers.IO) {
            repository.addPicture(picture)
        }
    }
    fun updatePicture(picture:Picture){
        viewModelScope.launch(Dispatchers.IO) {
            repository.updatePicture(picture)
        }
    }
    fun deletePicture(index:Int){
        if(index < 0 || index >= models.value!!.size) return
        viewModelScope.launch(Dispatchers.IO){
            val picture = models.value!![index]
            repository.deletePicture(picture)
            FileUtils().deleteFile(picture.url)
        }
    }
}